package com.tuzhi.sys.web.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.dtflys.forest.annotation.Get;
import com.tuzhi.auth.vo.LoginUser;
import com.tuzhi.auth.vo.UserBaseInfo;
import com.tuzhi.auth.vo.UserInfo;
import com.tuzhi.base.jpa.domain.Pager;
import com.tuzhi.base.jpa.healper.QueryHelper;
import com.tuzhi.base.service.BaseService;
import com.tuzhi.base.web.controller.SimpleBaseController;
import com.tuzhi.base.web.helper.AjaxResultHelper;
import com.tuzhi.base.web.vo.AjaxResultVO;
import com.tuzhi.base.web.vo.PageVO;
import com.tuzhi.common.domain.LoginUserBO;
import com.tuzhi.common.domain.ResultBO;
import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.common.helper.ResultHelper;
import com.tuzhi.security.service.impl.TokenServiceImpl;
import com.tuzhi.sys.jpa.entity.SysOrgEntity;
import com.tuzhi.sys.jpa.entity.SysUserEntity;
import com.tuzhi.sys.scurity.AuthService;
import com.tuzhi.sys.service.SysRoleService;
import com.tuzhi.sys.service.SysUserRoleService;
import com.tuzhi.sys.service.SysUserService;
import com.tuzhi.util.StringTzUtil;
import com.tuzhi.util.UserContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/sys/user")
@Api(tags = "用户")
@Slf4j
public class SysUserController extends SimpleBaseController<SysUserEntity, Long, SysUserEntity> {

    @Autowired
    SysUserService service;

    @Autowired
    SysRoleService roleService;

    @Autowired
    TokenServiceImpl tokenService;

    @Autowired
    SysUserRoleService userRoleService;

    @Autowired
    AuthService authService;

    @Override
    protected BaseService getThisService() {
        return service;
    }
/*
    @GetMapping(value = {"/find/{id}"})
    public SysUserEntity find(@PathVariable(value = "id", required = true) Long id, HttpServletRequest request) {

        log.info("===========" + request.getHeader("test") + "==========");
        String tzUserInfo = request.getHeader("tzUserInfo");


        Enumeration<String> e = ServletUtil.getRequest().getHeaderNames();
        while (e.hasMoreElements()) {
            log.info("name:{}", e.nextElement());
        }

        SysUserEntity entity = service.findById(id);
        return entity;
    }

    @GetMapping(value = {"/testAdd/{id}"})
    public SysUserEntity testAdd(@PathVariable(value = "id", required = true) Long id) {
        SysUserEntity entity = service.findById(id);
        SysRoleEntity roleEntity = new SysRoleEntity();
        roleEntity.setName("test" + RandomUtils.nextInt());
        roleEntity.setStatus(0);
        roleEntity.setTitle("测试角色");
        //entity.getRoles().add(roleEntity);
        service.save(entity);
        return entity;
    }

    @GetMapping(value = {"/test/putRoles"})
    public AjaxResultVO putRoles(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        Long userId = jsonObject.getLong("userId");
        List<Long> list = jsonObject.getList("roleIds", Long.class);
        if (ObjectTzUtil.existNull(userId, list)) {
            return AjaxResultHelper.build(ResultConstant.ERR_PARAM_NULL);
        }
        service.putRoles(userId, list);
        return AjaxResultHelper.success();
    }

    @GetMapping(value = {"/test/moveOutRoles"})
    public AjaxResultVO moveOutRoles(@RequestBody String json) {
        JSONObject jsonObject = JSON.parseObject(json);
        Long userId = jsonObject.getLong("userId");
        List<Long> list = jsonObject.getList("roleIds", Long.class);
        if (ObjectTzUtil.existNull(userId, list)) {
            return AjaxResultHelper.build(ResultConstant.ERR_PARAM_NULL);
        }
        service.moveOutRoles(userId, list);
        return AjaxResultHelper.success();
    }*/

    @ApiOperation("获取当前登录用户的基本信息")
    @GetMapping("/getCurUser")
    public LoginUser getCurUser() {
        try {
            LoginUserBO loginUserBO = tokenService.getCurUser();
            if (loginUserBO == null) {
                throw new BusinessException("获取用户身份失败,可能token 过期");
            }
            LoginUser curLoginUser = new LoginUser();
            curLoginUser.setRoleSet(loginUserBO.getRoles());
            curLoginUser.setSupper(loginUserBO.isSupper());
            curLoginUser.setOrgId(loginUserBO.getDeptId());
            curLoginUser.setUserName(loginUserBO.getUserName());
            curLoginUser.setNickName(loginUserBO.getNickName());
            curLoginUser.setTel(loginUserBO.getTel());
            curLoginUser.setDeptMgr(loginUserBO.isDeptMgr());
            curLoginUser.setUserId(loginUserBO.getUserId());
            return curLoginUser;
        } catch (Exception ex) {
            log.error("获取用户信息异常：{}", ExceptionUtils.getRootCauseStackTrace(ex));
        }
        return null;
    }

    @ApiOperation("获取当前登录用户")
    @PostMapping(value = "/getLoginUser")
    public LoginUserBO getLoginUser(@RequestParam("token") String token) {
        return tokenService.getLoginUser(token);
    }

    @ApiOperation("刷新Token")
    @PostMapping(value = "/tokenIsExpRefresh")
    public String tokenIsExpRefresh(@RequestParam("token") String token) {
        return tokenService.tokenIsExpRefresh(token);
    }


    @ApiOperation("修改用户密码")
    @PutMapping("/modifyPwd")
    public AjaxResultVO modifyPwd(@RequestBody String json) {

        JSONObject jsonObject = JSON.parseObject(json);
        String oldPwd = jsonObject.getString("oldPwd");
        String newPwd = jsonObject.getString("newPwd");
        if (StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(newPwd)) {
            throw new BusinessException("新密码，旧密码不能为空");
        }
        //TODO Test
        LoginUserBO loginUserBO=new LoginUserBO();
        loginUserBO.setUserName("admin");
//        LoginUserBO loginUserBO = tokenService.getCurUser();
        if (loginUserBO == null) {
            throw new BusinessException("获取用户身份失败,可能token 过期");
        }
        service.modifyPwd(oldPwd, newPwd, loginUserBO.getUserName());
        return AjaxResultHelper.success();
    }

    @ApiOperation("管理员修改用户密码")
    @PutMapping("/modifyPwd4Admin")
    public AjaxResultVO modifyPwd4Admin(@RequestBody UserInfo userInfo) {
        if (userInfo == null && StringUtils.isEmpty(userInfo.getPwd())) {
            throw new BusinessException("用户密码信息不能为空");
        }
        LoginUserBO loginUserBO = UserContext.getUserInfo(true);
        if (loginUserBO == null) {
            throw new BusinessException("获取用户身份失败,可能token 过期");
        }
        if (!loginUserBO.isDeptMgr() && !loginUserBO.isSupper()) {
            throw new BusinessException("没有权限重置密码");
        }
        service.modifyPwd4Amin(userInfo.getPwd(), userInfo.getUserName());
        return AjaxResultHelper.success();
    }

    /**
     * 通过用户名，获取用户的基础信息
     *
     * @param userName
     * @return
     */
    @ApiOperation("通过用户名，获取用户的基础信息")
    @GetMapping("/getUserOfUserName/{userName}")
    public UserBaseInfo getUserOfUserName(@PathVariable("userName") String userName) {
        SysUserEntity sysUserEntity = service.getUserByUserName(userName);
        if (sysUserEntity != null) {
            UserBaseInfo userBaseInfo = new UserBaseInfo();
            userBaseInfo.setUserName(sysUserEntity.getUsername());
            userBaseInfo.setUserId(sysUserEntity.getId());
            userBaseInfo.setOrgId(sysUserEntity.getOrgId());
            userBaseInfo.setTel(sysUserEntity.getPhone());
            userBaseInfo.setNickName(sysUserEntity.getNickname());
            return userBaseInfo;
        }

        return null;

    }

    /**
     * 通过用户Id，获取用户的基础信息
     *
     * @param userId
     * @return
     */
    @Get("/getUserOfUserId/{userId}")
    UserBaseInfo getUserOfUserId(@PathVariable("userId") Long userId) {
        return null;
    }

    @Override
    protected Pager<SysUserEntity> pagerVoCreateWhere(PageVO<SysUserEntity> pageVO, Pager<SysUserEntity> pager) {
        LoginUserBO curLoginUser = UserContext.getUserInfo(true);
//        SysUserEntity queryEntity = pageReqData2Bean(pageVO.getReqData(), SysUserEntity.class);
        SysUserEntity queryEntity = pageVO.getReqData();
        QueryHelper.Builder<SysUserEntity> queryBuilder = new QueryHelper.Builder<>();
        if (queryEntity != null) {
            queryBuilder.eq(SysUserEntity::getId, queryEntity.getId(), queryEntity.getId() != null);
            queryBuilder.lk(SysUserEntity::getUsername, queryEntity.getUsername(), StringTzUtil.isNotBlankNull(queryEntity.getUsername()));
            queryBuilder.lk(SysUserEntity::getNickname, queryEntity.getNickname(), StringTzUtil.isNotBlankNull(queryEntity.getNickname()));
        }
        //超级管理员，查询所有的客户
        // 其它的只能查询到自己所在org的记录
        if (!curLoginUser.isSupper()) {
            queryBuilder.eq(SysUserEntity::getOrgId, curLoginUser.getOrgId(), curLoginUser.getOrgId() != null);
        }
        queryBuilder.sortDesc(SysUserEntity::getId);
        pager.setWhereConditionBO(queryBuilder.build().getWhereConditionBO());
        return pager;
    }

    @ApiOperation("保存/修改用户信息，如果是修改把用户ID带上")
    @PutMapping({"/save"})
    @Override
    public ResultBO save(@RequestBody SysUserEntity entity) {
        if (entity == null) {
            throw new BusinessException("参数不能为空");
        }
        if (StringUtils.isBlank(entity.getUsername())) {
            throw new BusinessException("登录帐号不能为空");
        }
        if (StringUtils.isBlank(entity.getNickname())) {
            throw new BusinessException("用户名不能为空");
        }
        if (entity.getOrgId() == null) {
            throw new BusinessException("组织不能为空");
        }
        service.saveUserAndRole(entity);
        return AjaxResultHelper.success();
    }


    @ApiOperation("通过用户ID查询此用户所具有的角色")
    @GetMapping({"/listUserRole/{userId}"})
    public AjaxResultVO listUserRole(@PathVariable("userId") Long userId) {
        AjaxResultVO ajaxResultVO = AjaxResultHelper.success();
        ajaxResultVO.setData(roleService.listUserRole(userId));
        return ajaxResultVO;
    }


    @ApiOperation("修改用户状态")
    @PostMapping("/modifyStauts/{userId}/{sysStatus}")
    public AjaxResultVO modifyPwd(@PathVariable("userId") Long userId, @PathVariable("sysStatus") Integer sysStatus) {
        LoginUser loginUser = getCurUser();
        if (!loginUser.isSupper()) {
            throw new BusinessException("需要超级管理员才可能操作");
        }
        service.modifyStauts(userId, sysStatus);
        return AjaxResultHelper.success();
    }


    @DeleteMapping({"del/{id}"})
    public ResultBO del(@PathVariable(value = "id", required = true) Long id) {
        authService.deleteUser(id);
        return ResultHelper.success();
    }
}
